package com.wing.res.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.common.enums.MaintenanceEnum;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.UniqueIdGeneratorUtil;
import com.wing.config.BaseDataInit;
import com.wing.device.model.entity.DeviceModel;
import com.wing.device.service.DeviceModelService;
import com.wing.platform.feign.PlatformClient;
import com.wing.product.model.entity.ProductDetail;
import com.wing.product.model.entity.ProductType;
import com.wing.product.model.entity.ProductUnitInfo;
import com.wing.product.model.response.ProductPlanningTreeVo;
import com.wing.product.service.ProductDetailService;
import com.wing.product.service.ProductTypeService;
import com.wing.product.service.ProductUnitService;
import com.wing.qualification.dao.QualificationDao;
import com.wing.qualification.model.entity.Qualification;
import com.wing.qualification.model.request.QualificationForm;
import com.wing.qualification.model.response.QualificationVO;
import com.wing.qualification.service.QualificationService;
import com.wing.res.dao.BenchmarkBookDao;
import com.wing.res.model.entity.*;
import com.wing.res.model.request.ResBenchmarkBookAddForm;
import com.wing.res.model.response.DeviceOrWorkVo;
import com.wing.res.model.response.DrawInfosVO;
import com.wing.res.model.response.ResBenchmarkBookDetailVo;
import com.wing.res.service.*;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.asn1.isismtt.x509.ProfessionInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 基准书-ServiceImpl
 *
 * @author xiayang
 */
@Service
@Slf4j
public class BenchmarkBookServiceImpl extends ServiceImpl<BenchmarkBookDao, BenchmarkBook> implements BenchmarkBookService {

    @Autowired
    private ResBenchmarkBookBomService resBenchmarkBookBomService;

    @Autowired
    private ResBenchmarkBookEchnologyService resBenchmarkBookEchnologyService;

    @Autowired
    private ResBenchmarkBookEchnologySkuService resBenchmarkBookEchnologySkuService;

    @Autowired
    private ResBenchmarkBookQualityService resBenchmarkBookQualityService;

    @Autowired
    private ResProductDrawService resProductDrawService;

    @Autowired
    private ResProductDrawFilesService resProductDrawFilesService;

    @Autowired
    private ResBenchmarkBookEchnologyQualityService resBenchmarkBookEchnologyQualityService;

    @Autowired
    private ProductDetailService productDetailService;

    @Autowired
    private ProductUnitService productUnitService;


    @Autowired
    private DeviceModelService deviceModelService;

    @Override
    public Page<BenchmarkBook> list(Page page, Map<String, Object> params) {
        List<BenchmarkBook> list = baseMapper.list(page, params);
        page.setRecords(list);
        return page;
    }

    /**
     * 生成基准书
     *
     * @param resBenchmarkBookAddForm 基准书信息
     * @return 1.生成成功 2.生成失败
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long generateBenchmarkBook(ResBenchmarkBookAddForm resBenchmarkBookAddForm) {
        //1. 添加基准书

        //2.查询这个物料的最终版本号 如果没有就是插入a
        String versionInterval = this.baseMapper.getMaxVersionBy(resBenchmarkBookAddForm.getProductDetailId());
        if (StrUtil.isNotEmpty((versionInterval))) {
            char lastChar = versionInterval.charAt(0);
            char nextChar = (char) (lastChar + 1);
            versionInterval = nextChar + "";
        } else if ("Z".equals(versionInterval)) {
            versionInterval = "Z";
        } else{
            versionInterval = "A";
        }
        BenchmarkBook benchmarkBook = new BenchmarkBook();
        BeanUtil.copyProperties(resBenchmarkBookAddForm, benchmarkBook);
        //默认已经初审
        benchmarkBook.setStatus(MaintenanceEnum.BenchmarkBookStatus.DCS.getCode());
        benchmarkBook.setCreateTime(LocalDateTime.now());
        benchmarkBook.setVersionInterval(versionInterval);
        benchmarkBook.setProductDetailId(resBenchmarkBookAddForm.getProductDetailId());
        benchmarkBook.setMakePerson(JwtUtils.getLoginUserId());
        String JZS = UniqueIdGeneratorUtil.generateUniqueId("BK", "yyyyMMdd", 1000, 9999);
        benchmarkBook.setCode(JZS);
        benchmarkBook.setMakePersonName(JwtUtils.getLoginUsername());
        boolean save = save(benchmarkBook);
        if (save) {
            //插入成品图纸版本 + 图纸表
            if (resBenchmarkBookAddForm.getDrawInfos() != null) {
                ResProductDraw resProductDraw = new ResProductDraw();
                resProductDraw.setCode(UniqueIdGeneratorUtil.generateUniqueId("TZ", "yyyyMMdd", 1000, 9999));
                resProductDraw.setCreateTime(LocalDateTime.now());
                resProductDraw.setUpdateTime(LocalDateTime.now());
                resProductDraw.setCreatorName(JwtUtils.getUsername());
                resProductDraw.setCreator(JwtUtils.getLoginUserId());
                resProductDraw.setIsDefault("1");
                resProductDraw.setTaskId(benchmarkBook.getId());
                resProductDraw.setProductDetailId(resBenchmarkBookAddForm.getProductDetailId());
                LocalDate currentDate = LocalDate.now();
                int currentYear = currentDate.getYear();
                resProductDraw.setVersionName("ver." + currentYear + "-" + 1);
                boolean saveFile = this.resProductDrawService.save(resProductDraw);
                if (saveFile) {
                    List<ResProductDrawFiles> resProductDrawFiles = new ArrayList<>();
                    for (DrawInfosVO drawInfo : resBenchmarkBookAddForm.getDrawInfos()) {
                        ResProductDrawFiles resProductDrawFile = new ResProductDrawFiles();
                        resProductDrawFile.setCreateTime(LocalDateTime.now());
                        resProductDrawFile.setUpdateTime(LocalDateTime.now());
                        resProductDrawFile.setCreatorName(JwtUtils.getUsername());
                        resProductDrawFile.setCreator(JwtUtils.getLoginUserId());
                        if (StrUtil.isNotEmpty(drawInfo.getDrawType())) {
                            resProductDrawFile.setDrawType(drawInfo.getDrawType());
                        }else{
                            resProductDrawFile.setDrawType(MaintenanceEnum.DrawTypeEnum.CPTZ.getCode());
                        }
                        resProductDrawFile.setDrawId(resProductDraw.getId());
                        resProductDrawFile.setFileUrl(drawInfo.getDrawUrl());
                        resProductDrawFile.setName(drawInfo.getDrawName());
                        resProductDrawFiles.add(resProductDrawFile);
                    }
                    this.resProductDrawFilesService.saveBatch(resProductDrawFiles);
                }
            }
            List<ResBenchmarkBookBom> bomList = resBenchmarkBookAddForm.getBomList();
            //2. 添加基准书bom
//            ResBenchmarkBookBom resBenchmarkBookBom = new ResBenchmarkBookBom();
//            resBenchmarkBookBom.setCreatorName(JwtUtils.getLoginUsername());
//            resBenchmarkBookBom.setCreateTime(LocalDateTime.now());
//            resBenchmarkBookBom.setCreator(JwtUtils.getLoginUserId());
//            resBenchmarkBookBom.setProductDetailId(resBenchmarkBookAddForm.getProductDetailId());
//            resBenchmarkBookBom.setSkuCode(resBenchmarkBookAddForm.getSkuCode());
//            //设置为根节点
//            resBenchmarkBookBom.setParentId(-1L);
//            resBenchmarkBookBom.setCount(0);
//            resBenchmarkBookBom.setIsFinal(false);
//            resBenchmarkBookBom.setIsDeleted(false);
//            resBenchmarkBookBom.setSkuCode(resBenchmarkBookAddForm.getSkuCode());
//            resBenchmarkBookBom.setHasChild(true);
//            resBenchmarkBookBom.setHasEnableChild(false);
//            resBenchmarkBookBom.setBookId(benchmarkBook.getId());
            if (CollectionUtil.isNotEmpty(bomList)) {
                bomList.forEach(info -> {
                    info.setCreatorName(JwtUtils.getLoginUsername());
                    info.setCreateTime(LocalDateTime.now());
                    info.setCreator(JwtUtils.getLoginUserId());
                    info.setBookId(benchmarkBook.getId());
                    Long productDetailId = info.getProductDetailId();
                    if (productDetailId != null) {
                        ProductDetail byId = productDetailService.getById(productDetailId);
                        if (byId != null) {
                            info.setSkuCode(byId.getSkuCode());
                        }
                    }
                });
            }
//            bomList.add(resBenchmarkBookBom);
            resBenchmarkBookBomService.saveBatch(bomList);

            //添加工艺工序
            List<ResBenchmarkBookEchnology> echnologyList = resBenchmarkBookAddForm.getEchnologyList();
            if (CollectionUtil.isNotEmpty(echnologyList)) {
                for (int i = 0; i < echnologyList.size(); i++) {
                    echnologyList.get(i).setCreatorName(JwtUtils.getLoginUsername());
                    int sorted = i + 1;
                    echnologyList.get(i).setSorted(sorted);
                    echnologyList.get(i).setCreateTime(LocalDateTime.now());
                    echnologyList.get(i).setCreator(JwtUtils.getLoginUserId());
                    echnologyList.get(i).setBookId(benchmarkBook.getId());
                    boolean save1 = resBenchmarkBookEchnologyService.save(echnologyList.get(i));
                    if (save1) {
                        //物料列表     
                        List<ResBenchmarkBookEchnologySku> skuList = echnologyList.get(i).getSkuList();
                        if (CollectionUtil.isNotEmpty(skuList)) {
                            for (ResBenchmarkBookEchnologySku resBenchmarkBookEchnologySku : skuList) {
                                resBenchmarkBookEchnologySku.setEchnologyId(echnologyList.get(i).getId());
                                resBenchmarkBookEchnologySku.setCreatorName(JwtUtils.getLoginUsername());
                                resBenchmarkBookEchnologySku.setCreateTime(LocalDateTime.now());
                                resBenchmarkBookEchnologySku.setCreator(JwtUtils.getLoginUserId());
                            }
                            resBenchmarkBookEchnologySkuService.saveBatch(skuList);
                        }
                        //质检项列表
                        List<ResBenchmarkBookEchnologyQuality> qualityList = echnologyList.get(i).getQualityList();
                        if (CollectionUtil.isNotEmpty(qualityList)) {
                            for (ResBenchmarkBookEchnologyQuality infoQuality : qualityList) {
                                infoQuality.setProcessId(echnologyList.get(i).getId());
                                infoQuality.setCreatorName(JwtUtils.getLoginUsername());
                                infoQuality.setCreateTime(LocalDateTime.now());
                                infoQuality.setCreator(JwtUtils.getLoginUserId());
                                infoQuality.setBookId(benchmarkBook.getId());
                            }
                            resBenchmarkBookEchnologyQualityService.saveBatch(qualityList);
                        }
                    }
                }
            }

            //添加成品质检
            List<ResBenchmarkBookQuality> qualityList = resBenchmarkBookAddForm.getQualityList();
            if (CollectionUtil.isNotEmpty(qualityList)) {
                qualityList.forEach(info -> {
                    info.setCreatorName(JwtUtils.getLoginUsername());
                    info.setCreateTime(LocalDateTime.now());
                    info.setCreator(JwtUtils.getLoginUserId());
                    info.setBookId(benchmarkBook.getId());
                    info.setProductDetailId(resBenchmarkBookAddForm.getProductDetailId());
                    String taskNo = UniqueIdGeneratorUtil.generateUniqueId("QUA", "yyyyMMdd", 1000, 9999);
                    info.setNo(taskNo);
                });
            }
            resBenchmarkBookQualityService.saveBatch(qualityList);
        }
        return benchmarkBook.getId() == null ? 0L : benchmarkBook.getId();
    }

    /**
     * 查询基准书详情
     *
     * @param id
     * @return
     */
    @Override
    public ResBenchmarkBookDetailVo detail(Long id, Map<String, Object> params) {

        List<DeviceOrWorkVo> fessionlist = deviceModelService.fessionlist();
        List<DeviceOrWorkVo> devicelist = deviceModelService.devicelist();
        Map<Long, String> deviceModel = devicelist.stream().collect(Collectors.toMap(DeviceOrWorkVo::getId, DeviceOrWorkVo::getDeviceName));
        Map<Long, String> fession = fessionlist.stream().collect(Collectors.toMap(DeviceOrWorkVo::getId, DeviceOrWorkVo::getDeviceName));

        //查询出单位信息
        List<ProductUnitInfo> infoList = productUnitService.list();
        Map<Long, String> unitMap = infoList.stream().collect(Collectors.toMap(ProductUnitInfo::getId, ProductUnitInfo::getName));



        //查询基准书基本信息
        ResBenchmarkBookDetailVo detailVo = this.baseMapper.getDetailBy(id, params);
        detailVo.setStatusName(MaintenanceEnum.BenchmarkBookStatus.getNameByCode(detailVo.getStatus()));
        if (ObjectUtil.isNotEmpty(detailVo)) {

            //查询图纸信息
            List<DrawInfosVO> drawInfos =  this.resProductDrawService.getDrawInfosBy(detailVo.getId());
            if (CollectionUtil.isNotEmpty(drawInfos)) {
                detailVo.setDrawInfos(drawInfos);
            }
            //1.查询bom信息
            List<ProductPlanningTreeVo> vos = this.resBenchmarkBookBomService.selectBomTreeByBook(id);
            detailVo.setBomList(vos);

            //2.查询检测项目信息
            QueryWrapper<ResBenchmarkBookQuality> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("book_id", id);
            queryWrapper.eq("is_deleted", false);
            List<ResBenchmarkBookQuality> qualityList = this.resBenchmarkBookQualityService.list(queryWrapper);
            detailVo.setQualityList(qualityList);

            //3.查询工艺工序信息
            QueryWrapper<ResBenchmarkBookEchnology> echnologyQueryWrapper = new QueryWrapper<>();
            echnologyQueryWrapper.eq("book_id", id);
            echnologyQueryWrapper.eq("is_deleted", false);
            echnologyQueryWrapper.orderByAsc("sorted");
            List<ResBenchmarkBookEchnology> echnologyList = this.resBenchmarkBookEchnologyService.list(echnologyQueryWrapper);
            if (CollectionUtil.isNotEmpty(echnologyList)) {
                //查询基准数工艺物料信息
                for (ResBenchmarkBookEchnology resBenchmarkBookEchnology : echnologyList) {
                    //物料
                    List<ResBenchmarkBookEchnologySku> skuList = resBenchmarkBookEchnologySkuService.getSkuListBy(resBenchmarkBookEchnology.getId());
                    if (skuList != null) {
                        skuList.forEach(sku -> {
                            if (CollectionUtil.isNotEmpty(unitMap) && sku.getBaseUnit() != null) {
                                sku.setBaseUnitName(unitMap.get(sku.getBaseUnit()));
                            }
                        });
                    }
                    resBenchmarkBookEchnology.setSkuList(skuList);
                    if (StrUtil.isNotEmpty(resBenchmarkBookEchnology.getWorkstationNature()) && "1".equals(resBenchmarkBookEchnology.getWorkstationNature())) {
                        if (StrUtil.isNotEmpty(resBenchmarkBookEchnology.getDeviceType())) {
                            String deviceType = resBenchmarkBookEchnology.getDeviceType();
                            if (StrUtil.isNotEmpty(deviceType)) {
                                resBenchmarkBookEchnology.setDeviceTypeName(deviceModel.get(Long.valueOf(deviceType)));
                            }
                        }
                    } else if (StrUtil.isNotEmpty(resBenchmarkBookEchnology.getWorkstationNature()) && "2".equals(resBenchmarkBookEchnology.getWorkstationNature())) {
                        if (StrUtil.isNotEmpty(resBenchmarkBookEchnology.getDeviceType())) {
                            String deviceType = resBenchmarkBookEchnology.getDeviceType();
                            if (StrUtil.isNotEmpty(deviceType)) {
                                resBenchmarkBookEchnology.setDeviceTypeName(fession.get(Long.valueOf(deviceType)));
                            }
                        }
                    }
                    //工序
                    QueryWrapper<ResBenchmarkBookEchnologyQuality> qualityQueryWrapper = new QueryWrapper<>();
                    qualityQueryWrapper.eq("book_id", id);
                    qualityQueryWrapper.eq("is_deleted", false);
                    qualityQueryWrapper.eq("process_id", resBenchmarkBookEchnology.getId());
                    List<ResBenchmarkBookEchnologyQuality> list = this.resBenchmarkBookEchnologyQualityService.list(qualityQueryWrapper);
                    resBenchmarkBookEchnology.setQualityList(list);
                }

            }

            detailVo.setEchnologyList(echnologyList);

        }
        return detailVo;
    }

    /**
     * 修改基准书
     *
     * @param resBenchmarkBookAddForm
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateBenchmarkBook(ResBenchmarkBookAddForm resBenchmarkBookAddForm) {
        //1. 添加基准书
        BenchmarkBook benchmarkBook = this.getById(resBenchmarkBookAddForm.getId());
        BeanUtil.copyProperties(resBenchmarkBookAddForm, benchmarkBook);
        //默认已经初审
        benchmarkBook.setMakePersonName(JwtUtils.getLoginUsername());
        boolean update = updateById(benchmarkBook);
        if (update) {
            if (CollectionUtil.isNotEmpty(resBenchmarkBookAddForm.getDrawInfos())) {
                //查询默认的
                QueryWrapper<ResProductDraw> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("task_id", benchmarkBook.getId());
                queryWrapper.eq("product_detail_id", benchmarkBook.getProductDetailId());
                queryWrapper.eq("is_default", 1);
                ResProductDraw one = this.resProductDrawService.getOne(queryWrapper);
                //如果有默认的
                if (ObjectUtil.isNotEmpty(one)) {
                    //是否跟现在有改变
                    one.setIsDefault("0");
                    one.setUpdateTime(LocalDateTime.now());
                    one.setModifierName(JwtUtils.getLoginUsername());
                    one.setModifier(JwtUtils.getLoginUserId());
                    boolean updateById = this.resProductDrawService.updateById(one);
                    if (updateById) {
                        ResProductDraw resProductDraw = new ResProductDraw();
                        resProductDraw.setCode(UniqueIdGeneratorUtil.generateUniqueId("TZ", "yyyyMMdd", 1000, 9999));
                        resProductDraw.setCreateTime(LocalDateTime.now());
                        resProductDraw.setUpdateTime(LocalDateTime.now());
                        resProductDraw.setCreatorName(JwtUtils.getUsername());
                        resProductDraw.setCreator(JwtUtils.getLoginUserId());
                        resProductDraw.setIsDefault("1");
                        resProductDraw.setTaskId(benchmarkBook.getId());
                        resProductDraw.setProductDetailId(resBenchmarkBookAddForm.getProductDetailId());
                        LocalDate currentDate = LocalDate.now();
                        int currentYear = currentDate.getYear();
                        if (StrUtil.isNotEmpty(one.getVersionName())) {
                            int num = Integer.parseInt(one.getVersionName().substring(one.getVersionName().indexOf("-") + 1)) + 1;
                            resProductDraw.setVersionName("ver." + currentYear + "-" + num);
                        }
                        boolean save = this.resProductDrawService.save(resProductDraw);
                        if (save) {
                            List<ResProductDrawFiles> resProductDrawFiles = new ArrayList<>();
                            for (DrawInfosVO drawInfo : resBenchmarkBookAddForm.getDrawInfos()) {
                                ResProductDrawFiles resProductDrawFile = new ResProductDrawFiles();
                                resProductDrawFile.setCreateTime(LocalDateTime.now());
                                resProductDrawFile.setUpdateTime(LocalDateTime.now());
                                resProductDrawFile.setCreatorName(JwtUtils.getUsername());
                                resProductDrawFile.setCreator(JwtUtils.getLoginUserId());
                                resProductDrawFile.setDrawId(resProductDraw.getId());
                                resProductDrawFile.setFileUrl(drawInfo.getDrawUrl());
                                if (StrUtil.isNotEmpty(drawInfo.getDrawType())) {
                                    resProductDrawFile.setDrawType(drawInfo.getDrawType());
                                }else{
                                    resProductDrawFile.setDrawType(MaintenanceEnum.DrawTypeEnum.CPTZ.getCode());
                                }
                                resProductDrawFile.setName(drawInfo.getDrawName());
                                resProductDrawFiles.add(resProductDrawFile);
                            }
                            this.resProductDrawFilesService.saveBatch(resProductDrawFiles);
                        }
                    }
                } else {
                    ResProductDraw resProductDraw = new ResProductDraw();
                    resProductDraw.setCode(UniqueIdGeneratorUtil.generateUniqueId("TZ", "yyyyMMdd", 1000, 9999));
                    resProductDraw.setCreateTime(LocalDateTime.now());
                    resProductDraw.setUpdateTime(LocalDateTime.now());
                    resProductDraw.setCreatorName(JwtUtils.getUsername());
                    resProductDraw.setCreator(JwtUtils.getLoginUserId());
                    resProductDraw.setIsDefault("1");
                    resProductDraw.setTaskId(benchmarkBook.getId());
                    resProductDraw.setProductDetailId(resBenchmarkBookAddForm.getProductDetailId());
                    LocalDate currentDate = LocalDate.now();
                    int currentYear = currentDate.getYear();
                    resProductDraw.setVersionName("ver." + currentYear + "-" + 1);
                    boolean save = this.resProductDrawService.save(resProductDraw);
                    //插入图片信息
                    if (save) {
                        List<ResProductDrawFiles> resProductDrawFiles = new ArrayList<>();
                        for (DrawInfosVO drawInfo : resBenchmarkBookAddForm.getDrawInfos()) {
                            ResProductDrawFiles resProductDrawFile = new ResProductDrawFiles();
                            resProductDrawFile.setCreateTime(LocalDateTime.now());
                            resProductDrawFile.setUpdateTime(LocalDateTime.now());
                            resProductDrawFile.setCreatorName(JwtUtils.getUsername());
                            resProductDrawFile.setCreator(JwtUtils.getLoginUserId());
                            resProductDrawFile.setDrawId(resProductDraw.getId());
                            if (StrUtil.isNotEmpty(drawInfo.getDrawType())) {
                                resProductDrawFile.setDrawType(drawInfo.getDrawType());
                            }else{
                                resProductDrawFile.setDrawType(MaintenanceEnum.DrawTypeEnum.CPTZ.getCode());
                            }
                            resProductDrawFile.setFileUrl(drawInfo.getDrawUrl());
                            resProductDrawFile.setName(drawInfo.getDrawName());
                            resProductDrawFiles.add(resProductDrawFile);
                        }
                        this.resProductDrawFilesService.saveBatch(resProductDrawFiles);
                    }
                }
            }
        }
        //删除基准书bom
        QueryWrapper<ResBenchmarkBookBom> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("book_id", benchmarkBook.getId());
        queryWrapper.eq("is_deleted", false);
        this.resBenchmarkBookBomService.remove(queryWrapper);
        List<ResBenchmarkBookBom> bomList = resBenchmarkBookAddForm.getBomList();
        if (CollectionUtil.isNotEmpty(bomList)) {
            for (ResBenchmarkBookBom info : bomList) {
                info.setCreatorName(JwtUtils.getLoginUsername());
                info.setCreateTime(LocalDateTime.now());
                info.setCreator(JwtUtils.getLoginUserId());
                info.setBookId(benchmarkBook.getId());
                Long productDetailId = info.getProductDetailId();
                if (productDetailId != null) {
                    ProductDetail byId = productDetailService.getById(productDetailId);
                    if (byId != null) {
                        info.setSkuCode(byId.getSkuCode());
                    }
                }
            }
        }
        resBenchmarkBookBomService.saveBatch(bomList);

        //3。添加工艺工序 （如果已经审核就不能动工序了）
        if (!benchmarkBook.getStatus().equals(MaintenanceEnum.BenchmarkBookStatus.DCS.getCode())) {
            List<ResBenchmarkBookEchnology> echnologyList = resBenchmarkBookAddForm.getEchnologyList();
            if (CollectionUtil.isNotEmpty(echnologyList)) {
//                for (ResBenchmarkBookEchnology info : echnologyList) {
                for (int i = 0; i < echnologyList.size(); i++) {
                    int sorted = i+1;
                    echnologyList.get(i).setSorted(sorted);
                    echnologyList.get(i).setCreatorName(JwtUtils.getLoginUsername());
                    echnologyList.get(i).setCreateTime(LocalDateTime.now());

                    echnologyList.get(i).setCreator(JwtUtils.getLoginUserId());
                    echnologyList.get(i).setBookId(benchmarkBook.getId());
                    boolean save = resBenchmarkBookEchnologyService.saveOrUpdate(echnologyList.get(i));
                    if (save) {
                        List<ResBenchmarkBookEchnologySku> skuList = echnologyList.get(i).getSkuList();
                        if (CollectionUtil.isNotEmpty(skuList)) {
                            //删除原来的
                            QueryWrapper<ResBenchmarkBookEchnologySku> skuQueryWrapper = new QueryWrapper<>();
                            skuQueryWrapper.eq("echnology_id", echnologyList.get(i).getId());
                            this.resBenchmarkBookEchnologySkuService.remove(skuQueryWrapper);

                            for (ResBenchmarkBookEchnologySku sku : skuList) {
                                sku.setEchnologyId(echnologyList.get(i).getId());
                                sku.setCreatorName(JwtUtils.getLoginUsername());
                                sku.setProductDetailId(sku.getProductDetailId());
                                sku.setCreateTime(LocalDateTime.now());
                                sku.setCreator(JwtUtils.getLoginUserId());
                            }
                            this.resBenchmarkBookEchnologySkuService.saveBatch(skuList);
                        }

                        //质检项列表
                        List<ResBenchmarkBookEchnologyQuality> qualityList = echnologyList.get(i).getQualityList();

                        if (CollectionUtil.isNotEmpty(qualityList)) {
                            QueryWrapper<ResBenchmarkBookEchnologyQuality> qualityQueryWrapper = new QueryWrapper<>();
                            qualityQueryWrapper.eq("book_id", benchmarkBook.getId());
                            qualityQueryWrapper.eq("process_id", echnologyList.get(i).getId());
                            this.resBenchmarkBookEchnologyQualityService.remove(qualityQueryWrapper);

                            for (ResBenchmarkBookEchnologyQuality infoQuality : qualityList) {
                                infoQuality.setProcessId(echnologyList.get(i).getId());
                                infoQuality.setCreatorName(JwtUtils.getLoginUsername());
                                infoQuality.setCreateTime(LocalDateTime.now());
                                infoQuality.setCreator(JwtUtils.getLoginUserId());
                                infoQuality.setBookId(benchmarkBook.getId());
                                if (ObjectUtil.isNotEmpty(infoQuality.getDetectionRate())) {
                                    infoQuality.setDetectionRate(BigDecimal.ZERO);
                                }
                            }
                            resBenchmarkBookEchnologyQualityService.saveBatch(qualityList);
                        }
                    }
                }
            }
        } else {
            QueryWrapper<ResBenchmarkBookEchnology> echnologyQueryWrapper = new QueryWrapper<>();
            echnologyQueryWrapper.eq("book_id", benchmarkBook.getId());
            echnologyQueryWrapper.eq("is_deleted", false);
            this.resBenchmarkBookEchnologyService.remove(echnologyQueryWrapper);

            List<ResBenchmarkBookEchnology> echnologyList = resBenchmarkBookAddForm.getEchnologyList();
            if (CollectionUtil.isNotEmpty(echnologyList)) {
//                for (ResBenchmarkBookEchnology info : echnologyList) {
                for (int i = 0; i < echnologyList.size(); i++) {
                    int sorted = i+1;
                    echnologyList.get(i).setSorted(sorted);
                    echnologyList.get(i).setCreatorName(JwtUtils.getLoginUsername());
                    echnologyList.get(i).setCreateTime(LocalDateTime.now());
                    echnologyList.get(i).setCreator(JwtUtils.getLoginUserId());
                    echnologyList.get(i).setBookId(benchmarkBook.getId());
                    boolean save = resBenchmarkBookEchnologyService.save(echnologyList.get(i));
                    if (save) {
                        List<ResBenchmarkBookEchnologySku> skuList = echnologyList.get(i).getSkuList();
                        if (CollectionUtil.isNotEmpty(skuList)) {
                            //删除原来的
                            QueryWrapper<ResBenchmarkBookEchnologySku> skuQueryWrapper = new QueryWrapper<>();
                            skuQueryWrapper.eq("echnology_id", echnologyList.get(i).getId());
                            this.resBenchmarkBookEchnologySkuService.remove(skuQueryWrapper);
                            for (ResBenchmarkBookEchnologySku sku : skuList) {
                                sku.setEchnologyId(echnologyList.get(i).getId());
                                sku.setCreatorName(JwtUtils.getLoginUsername());
                                sku.setProductDetailId(sku.getProductDetailId());
                                sku.setCreateTime(LocalDateTime.now());
                                sku.setCreator(JwtUtils.getLoginUserId());
                            }
                            this.resBenchmarkBookEchnologySkuService.saveBatch(skuList);
                        }

                        //质检项列表
                        List<ResBenchmarkBookEchnologyQuality> qualityList = echnologyList.get(i).getQualityList();
                        if (CollectionUtil.isNotEmpty(qualityList)) {
                            //删除质检项
                            QueryWrapper<ResBenchmarkBookEchnologyQuality> qualityQueryWrapper = new QueryWrapper<>();
                            qualityQueryWrapper.eq("book_id", benchmarkBook.getId());
                            qualityQueryWrapper.eq("process_id", echnologyList.get(i).getId());
                            this.resBenchmarkBookEchnologyQualityService.remove(qualityQueryWrapper);

                            for (ResBenchmarkBookEchnologyQuality infoQuality : qualityList) {
                                infoQuality.setProcessId(echnologyList.get(i).getId());
                                infoQuality.setCreatorName(JwtUtils.getLoginUsername());
                                infoQuality.setCreateTime(LocalDateTime.now());
                                infoQuality.setCreator(JwtUtils.getLoginUserId());
                                infoQuality.setBookId(benchmarkBook.getId());
                                if (ObjectUtil.isNotEmpty(infoQuality.getDetectionRate())) {
                                    infoQuality.setDetectionRate(BigDecimal.ZERO);
                                }
                            }
                            resBenchmarkBookEchnologyQualityService.saveBatch(qualityList);
                        }
                    }
                }
            }
        }

        //添加成品质检
        QueryWrapper<ResBenchmarkBookQuality> qualityQueryWrapper = new QueryWrapper<>();
        qualityQueryWrapper.eq("book_id", benchmarkBook.getId());
        qualityQueryWrapper.eq("is_deleted", false);
        this.resBenchmarkBookQualityService.remove(qualityQueryWrapper);

        List<ResBenchmarkBookQuality> qualityList = resBenchmarkBookAddForm.getQualityList();
        if (CollectionUtil.isNotEmpty(qualityList)) {
            qualityList.forEach(info -> {
                info.setCreatorName(JwtUtils.getLoginUsername());
                info.setCreateTime(LocalDateTime.now());
                info.setCreator(JwtUtils.getLoginUserId());
                info.setBookId(benchmarkBook.getId());
                String taskNo = UniqueIdGeneratorUtil.generateUniqueId("QUA", "yyyyMMdd", 1000, 9999);
                info.setNo(taskNo);
            });
        }
        resBenchmarkBookQualityService.saveBatch(qualityList);
        return 1;
    }


    /**
     * 修改基准书状态
     *
     * @param id
     * @param status
     * @return
     */
    @Override
    public int benchmarkBookChange(Long id, String status) {
        BenchmarkBook byId = this.getById(id);
        byId.setStatus(status);
        //已终审
        if (status.equals(MaintenanceEnum.BenchmarkBookStatus.DZS.getCode())) {
            byId.setAuditTime(LocalDateTime.now());
            byId.setAuditPerson(JwtUtils.getLoginUserId());
        } else if (status.equals(MaintenanceEnum.BenchmarkBookStatus.DJD.getCode())) {
            byId.setAdjustTime(LocalDateTime.now());
            byId.setAdjustPerson(JwtUtils.getLoginUserId());
        } else if (status.equals(MaintenanceEnum.BenchmarkBookStatus.YDX.getCode())) {
            byId.setAuthorizePerson(JwtUtils.getLoginUserId());
            byId.setAuthorizeTime(LocalDateTime.now());
        }
        return this.baseMapper.updateById(byId);
    }

    /**
     * 作废基准书
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int voidBook(Long id) {
        BenchmarkBook byId = this.getById(id);
        byId.setStatus(MaintenanceEnum.BenchmarkBookStatus.YZF.getCode());
        return this.baseMapper.updateById(byId);
    }
}
